package com.snowy.hidden.util;

import com.snowy.framework.util.HexUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SHA加密
 * @author hjl
 */
@Slf4j
@Data
public class ShaUtil {

    public static void main(String[] args) {

    }

    /**
     * SHA256加密
     * @param str 加密字符串
     * @return
     */
    public static String getSha256(String str) {
        MessageDigest messageDigest;
        String encodestr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodestr = HexUtil.bytes2HexStr(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodestr;
    }

    /**
     * HMACSHA256加密
     * @param data 加密字符串
     * @param key 加密密钥
     * @return
     */
    public static String getHmacSha256(String data, String key) {
        byte[] array = new byte[0];
        try {
            Mac sha256Hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
            sha256Hmac.init(secretKey);
            array = sha256Hmac.doFinal(data.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            log.error("==HmacSha256=1="+e.getMessage());
        } catch (UnsupportedEncodingException e) {
            log.error("==HmacSha256=2="+e.getMessage());
        } catch (InvalidKeyException e) {
            log.error("==HmacSha256=3="+e.getMessage());
        }
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

}
